const { exec } = require('../db/mysql');
const qs = require('qs');

const createComment = function(data) {
  if (!data.blogId) {
    data.blogId = null;
  }
  const { id, date, ownerId, fromId, fromName, fromAvatar, likeNum, content, blogId } = data;
  let sql =  `insert into comments (id, date, ownerId, fromId, fromName, fromAvatar, likeNum, content, blogId) values ('${id}', '${date}', '${ownerId}', '${fromId}', '${fromName}', '${fromAvatar}', '${likeNum}', '${content}', ${blogId});`;
  console.log('sql=======', sql);
  return exec(sql).then(rows => {
    return Promise.resolve(rows[0] || {});
  }).catch(err => {
    return Promise.reject("向数据库插入评论数据失败", err);
  })

};

const getComments = (blogId) => {
  const id = blogId;
  console.log('blogId', id);
  let sql = 'select * from comments where 1=1 ';
  if (id) {
    sql += `and blogId = ${id} ;`;
  }
  return exec(sql).then(comments => {
    comments = JSON.parse(JSON.stringify(comments));
    return Promise.resolve(comments)
  }).catch(err => {
    return Promise.reject('获取评论失败')
  })
};

const updateComment = (comment) => {
  const id = comment.id;
  const reply = JSON.stringify(qs.parse(comment).reply);
  let sql = `
    update comments set reply='${reply}' where id='${id}';
  `;
  return exec(sql).then(data => {
    return Promise.resolve('更新reply成功');
  }).catch(err => {
    return Promise.reject('更新reply失败');
  })
};

const updateLikeNum = (item) => {
  const id = item.id;
  const likeNum = item.likeNum;
  let sql = `
    update comments set likeNum='${likeNum}' where id='${id}';
  `;
  return exec(sql).then(data => {
    return Promise.resolve('更新likeNum成功');
  }).catch(err => {
    return Promise.reject('更新likeNum失败');
  })
};
module.exports = { createComment, getComments, updateComment, updateLikeNum };